﻿using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using FileService.model;

namespace FileService.common
{
    /// <summary>
    /// SharpZip操作类
    /// </summary>
    public class SharpZipLibUtil
    {


        /// <summary>
        /// 压缩多个文件
        /// </summary>
        /// <param name="zipBaseInfo">压缩信息</param>
        /// <returns></returns>
        public bool MakeFilesZip(ZipBaseInfo zipBaseInfo)
        {
            FileStream fileStream = File.Create(zipBaseInfo.Path + "/" + zipBaseInfo.Name);
            ZipOutputStream outputStream = new ZipOutputStream(fileStream);
            try
            {
                //是否有压缩密码
                if (!StringHelper.IsEmpty(zipBaseInfo.Password))
                {
                    outputStream.Password = zipBaseInfo.Password;
                }
                //是否有压缩级别
                if (!StringHelper.IsEmpty(zipBaseInfo.Level))
                {
                    outputStream.SetLevel(zipBaseInfo.Level);
                }
                for (int i = 0; i < zipBaseInfo.RealFilePaths.Count; i++)
                {
                    ZipEntry zipEntry = new ZipEntry(zipBaseInfo.ZipFilePaths[i]);
                    //创建压缩包内文件
                    outputStream.PutNextEntry(zipEntry);
                    var buffer = new byte[5 * 1024];
                    //文件流写入
                    using (FileStream write = File.OpenRead(zipBaseInfo.RealFilePaths[i]))
                    {
                        StreamUtils.Copy(write, outputStream, buffer);
                    }
                    outputStream.CloseEntry();
                }
                outputStream.Close();
                fileStream.Close();
                return true;
            }
            catch (Exception)
            {
                outputStream.Close();
                fileStream.Close();
                return false;
            }

        }

        /// <summary>
        /// 异步压缩多个文件
        /// </summary>
        /// <param name="zipBaseInfo">压缩信息</param>
        /// <returns></returns>
        public async Task<bool> MakeFilesZipAsync(ZipBaseInfo zipBaseInfo)
        {
            return await Task.Run(() => MakeFilesZip(zipBaseInfo));
        }
    }
}
